import {
  CallHandler,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { RedisService } from '../redis.service';
import { IS_PUBLIC_KEY, SYS_NAME_EN } from '../constants';

@Injectable()
export class TokenStateInterceptor implements NestInterceptor {
  constructor(
    private readonly redisService: RedisService,
    private reflector: Reflector,
  ) {}

  async intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Promise<Observable<any>> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!isPublic) {
      const request = context.switchToHttp().getRequest();
      const redisTokenKey = `${SYS_NAME_EN}-${request.user.userId}-${request.user.username}`;
      const redisToken = await this.redisService.getValue(redisTokenKey);
      if (
        !redisToken ||
        redisToken !== request.headers.authorization.split(' ')[1]
      ) {
        throw new HttpException(
          'Other clients logged in',
          HttpStatus.UNAUTHORIZED,
        );
      }
    }
    return next.handle();
  }
}
